package 第二章数据结构.堆.id838堆排序;

import java.util.Scanner;

/**
 * 小根堆
 */
public class Main {
    public static void main(String[]args){
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        int m = scanner.nextInt();
        int []nums = new int[n];
        for(int i = 0;i<n;i++){
            nums[i] = scanner.nextInt();
        }
        MyHeap heap = new MyHeap(nums);
        while (m -- > 0){
            System.out.print(heap.poll()+ " ");
        }

    }

    static class MyHeap{
        static int[] arrays;
        static int index;
        //构建堆
        MyHeap(int[] nums){
            arrays = nums;
            int n = nums.length;
            index = n;
            for(int i = n/2;i>=0;i--){
                down(i);
            }
        }
        //弹出堆顶元素
        public static int poll(){
            int ret = arrays[0];
            arrays[0] = arrays[index-1];
            down(0);
            index--;
            return ret;
        }

        //up操作
        public static void up(int k){
            //父节点
            int parent = (k-1)/2;
            if(arrays[parent] > arrays[k]){
                swap(parent, k);
                up(parent);
            }
        }

        //down操作
        public static void down(int k){
            //左右节点
            int left = 2 * k +1;
            int right = 2 * k + 2;
            int min = k;
            //左右节点存在
            while (left < index  && arrays[left] < arrays[min]){
                min = left;
            }
            while (right < index && arrays[right] < arrays[min]){
                min = right;
            }
            if(min != k){
                swap(min, k);
                down(min);
            }
        }

        public static void swap(int a , int b){
            int x = arrays[a];
            arrays[a] = arrays[b];
            arrays[b] = x;
        }
    }

}
